﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using He.Common;
using LitJson;
using Newtonsoft.Json;

namespace He.API.WeiXin
{
    public class UploadHandle
    {
        /// <summary>
        /// 上传多媒体文件,返回 MediaId 
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="type"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string UploadMedia(string type, string filePath)
        {
            string access_token = CheckSignature.GetAccessToken();
            string result = "";
            bool isHttpFile = false;
            string posturl = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type=" + type;
            if (filePath.ToLower().StartsWith("http://"))
            {
                isHttpFile = true;
                //下载并存储远程文件
                string fileExt = FileHelper.GetFileExt(filePath);
                string fname = FileHelper.MakeFileName(fileExt);
                string dirName = FileHelper.MakeUploadDire(Config.webset.web_path, "temp", 0);
                string fullSavePath = dirName + fname;
                FileHelper.DownloadFile(filePath, fullSavePath);
                filePath = fullSavePath;
            }
            if (!FileHelper.Exists(filePath))
            {
                return "error";
            }
            string absoluteFilePath = PathHelper.MapPath(filePath);
            WebClient client = new WebClient();
            client.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                byte[] responseArray = client.UploadFile(posturl, "POST", absoluteFilePath);
                result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length);
                Media media = JsonMapper.ToObject<Media>(result);
                if (result.Contains("errcode"))
                {
                    result = "error";
                }
                else
                {
                    if (media.type == Enums.MediaType.thumb.ToString())
                    {
                        result = media.thumb_media_id;
                    }
                    else
                    {
                        result = media.media_id;
                    }
                }
            }
            catch (Exception ex)
            {
                result = "error";
            }
            finally
            {
                if (isHttpFile == true)
                {
                    //删除临时下载文件
                    FileHelper.DeleteFile(filePath);
                }
            }
            return result;
        }

        /// <summary>
        /// 上传图文消息素材,返回 MediaId 
        /// </summary>
        /// <param name="lst"></param>
        /// <returns></returns>
        public static string UploadArticle(List<Model.article> lst)
        {
            string posturl = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=" + CheckSignature.GetAccessToken();
            Articles obj = new Articles();
            obj.articles = new List<Article>();
            Article article;
            foreach (Model.article item in lst)
            {
                article = new Article();
                article.thumb_media_id = UploadMedia(Enums.MediaType.thumb.ToString(), item.img_url);
                article.author = "";
                article.title = item.title;
                article.content_source_url = item.link_url;
                article.content = item.content;
                article.digest = item.seo_desc;
                article.show_cover_pic = "1";
                if (article.thumb_media_id != "error")
                {
                    obj.articles.Add(article);
                }
            }
            JsonSerializerSettings settings = new JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore };
            string json = JsonConvert.SerializeObject(obj, settings);
            string result = HttpHelper.HttpPost(posturl, json);
            Article res = new Article();
            res = JsonConvert.DeserializeObject<Article>(result);
            return res.media_id;
        }
    }
}
